package com.cloud.cop.marshaller;

import java.io.IOException;
import java.io.OutputStream;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

import com.cloud.cop.CopResponse;
import com.cloud.cop.CopResponseMarshaller;


/**
 * <pre>
 *    将{@link com.cop.CopResponse}流化成JSON
 * </pre>
 * @author
 * @version 1.0
 */
public class JacksonJsonCopResponseMarshaller implements CopResponseMarshaller{

	private ObjectMapper objectMapper;
	
	/**
	 * 将对象进行格式化输出
	 */
	public void marshaller(CopResponse response, OutputStream outputStream) {
		try {
			JsonGenerator jsonGenerator = getObjectMapper().getJsonFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8);
			getObjectMapper().writeValue(jsonGenerator, response);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 获得ObjectMapper
	 * @return
	 */
	private ObjectMapper getObjectMapper(){
		if(objectMapper==null){
			ObjectMapper objectMapper = new ObjectMapper();
			AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
			SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
			serializationConfig = serializationConfig.with(SerializationConfig.Feature.WRAP_ROOT_VALUE)
            .withAnnotationIntrospector(introspector);
			objectMapper.setSerializationConfig(serializationConfig);
            this.objectMapper = objectMapper;
		}
		return this.objectMapper;
	}
	
}

